package dk.hewison.client.data.request;

import com.google.gwt.http.client.*;
import com.google.gwt.json.client.*;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import dk.hewison.client.Log;
import dk.hewison.client.data.MediaServerAsync;
import dk.hewison.client.domain.Directory;

/**
 * @author John Hewison
 * @author $LastChangedBy: john.hewison $:  $ $LastChangedDate: 2009-02-07 20:27:07 +0000 (Sat, 07 Feb 2009) $:
 * @version $Revision: 362 $:
 */

public class MyRequestBuilder implements MediaServerAsync {

    public static final String DEFAULT_FOLDER_NAME = "./";

    private void setFilenames(Directory directory, String text, AsyncCallback<Directory> asyncCallback) {
        String[] imageNames = text.split("\n");
        for (String imageName : imageNames) {
            directory.addPhoto(imageName);
        }

        directory.setLoaded();
        asyncCallback.onSuccess(directory);
    }

    public void getDirectoryImageNames(final Directory directory, final AsyncCallback<Directory> asyncCallback) {
        String url = directory.getAbsolutePath() + "/.images.txt";
        //log("initAlbums() " + url);
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
        builder.setHeader("Content-type", "text/html; charset=utf-8");

        try {
            builder.sendRequest(null, new RequestCallback() {
                public void onError(Request request, Throwable exception) {
                    // Couldn't connect to server (could be timeout, SOP violation, etc.)
                    Log.error("RequestCallback Error " + exception.toString());
                    Window.alert("GetMyStuff.onResponseReceived error");
                }

                public void onResponseReceived(Request request, Response response) {
                    if (200 == response.getStatusCode()) {
                        Log.debug("GetMyStuff.onResponseReceived " + response.getText());
                        setFilenames(directory, response.getText(), asyncCallback);
                        // Process the response in response.getText()
                    } else {
                        // Handle the error.  Can get the status text from response.getStatusText()
                        Log.debug("onResponseReceived Error " + response.getStatusText() + ": " + response.getText());
                        setFilenames(directory, response.getText(), asyncCallback);
                    }
                }
            });
        } catch (RequestException e) {
            // Couldn't connect to server
            Window.alert("GetMyStuff.onResponseReceived error");
            Log.error("Error " + e.toString());
        }
    }

    /* String json = "{\n" +
"    \"name\" : \"John\",\n" +
"    \"albums\" : [\n" +
"        {\n" +
"            \"folderName\": \"1\", \"name\": \"hello\", \"caption\": \"Well\",  \"description\": \"\", \"coverPhoto\": \"P1000379.jpg\"\n" +
"        },{\n" +
"            \"folderName\": \"2\",\n" +
"            \"name\": \"jul\",\n" +
"            \"caption\": \"What\",\n" +
"            \"description\": \"\",\n" +
"            \"coverPhoto\": \"P1000379.jpg\"\n" +
"        }\n" +
"    ]}";*/


    public void getDirectory(final Directory directory, final AsyncCallback<Directory> callback) {
        String directoryPath;
        if (directory == null) {
            directoryPath = "";
        } else {
            directoryPath = directory.getAbsolutePath();
        }

        String url = DEFAULT_FOLDER_NAME + directoryPath + "/.dir.json";
        //log("initAlbums() " + url);
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));

        try {
            builder.sendRequest(null, new RequestCallback() {
                public void onError(Request request, Throwable exception) {
                    // Couldn't connect to server (could be timeout, SOP violation, etc.)
                    Log.error("RequestCallback Error " + exception.toString());
                    Window.alert("GetMyStuff.onResponseReceived error");
                }

                public void onResponseReceived(Request request, Response response) {
                    if (200 == response.getStatusCode()) {
                        Log.debug("GetMyStuff.onResponseReceived " + response.getText());
                        JSONValue jsonValue = JSONParser.parse(response.getText());
                        createSubDirectories(directory, jsonValue, callback);
                        // Process the response in response.getText()
                    } else {
                        // Handle the error.  Can get the status text from response.getStatusText()
                        Log.debug("onResponseReceived Error " + response.getStatusText() + ": " + response.getText());
                        JSONValue jsonValue = JSONParser.parse(response.getText());
                        createSubDirectories(directory, jsonValue, callback);
                    }
                }
            });
        } catch (RequestException e) {
            // Couldn't connect to server
            Window.alert("GetMyStuff.onResponseReceived error");
            Log.error("Error " + e.toString());
        }

    }

    /**
     * {"name": "2009","albums":[
     * {"folderName": "01:01:2009","hasImages": "true","coverPhoto": "MEMO0010.JPG"},
     * {"folderName": "04:01:2009","hasImages": "true","coverPhoto": "P1000592.JPG"}]}
     *
     * @param directory the directory
     * @param jsonValue jsonValue
     * @param callback  callback
     */
    private void createSubDirectories(Directory directory, JSONValue jsonValue, AsyncCallback<Directory> callback) {

        JSONObject jsonObject = (JSONObject) jsonValue;

        if (directory == null) {
            JSONString name = (JSONString) jsonObject.get("name");
            directory = new Directory(name.stringValue());
        }

        JSONArray jsonArray = (JSONArray) jsonObject.get("subdir");

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonAlbumObject = (JSONObject) jsonArray.get(i);
            JSONString folderName = (JSONString) jsonAlbumObject.get("folderName");
            //JSONString name = (JSONString) jsonAlbumObject.get("name");
            //JSONString caption = (JSONString) jsonAlbumObject.get("caption");
            //JSONString description = (JSONString) jsonAlbumObject.get("description");
            JSONString coverPhoto = (JSONString) jsonAlbumObject.get("coverPhoto");

            Directory subDirectory = new Directory(folderName.stringValue());
            //directory.setCaption(caption.stringValue());            
            //directory.setDescription(description.stringValue());
            subDirectory.setCoverPhotoName(coverPhoto.stringValue());

            directory.add(subDirectory);
        }

        if (callback != null) {
            callback.onSuccess(directory);
        }


    }

    public static void main(String[] args) {
        //new MyRequestBuilder().getUserInfo(null);
    }
}
